<script type="text/javascript">
$(function(){
	var pg = App.deploy.deployIndex.ui, pp = pg.params,
		tabs = pg.find('.tabs'), tabTpl = pg.children('.envTab'),
		itemTpl = pg.children('.itemPl'),
		envs = $.map(Cache.base.env('deploy'), function(env, i){
			if (!App.logon.power('deploy.' + env)) {
				return null;
			}
			return env;
		}).join(','),
		deploying = null;
	
	function adjust(){
		var p = pg.parent(), h = p.height(),
			m = tabs.find('.body>.main');
		pg.height(h);
		tabs.width(p.width() - 25);
		tabs.height(h - 4);
		tabs.adjust();
		m.find('.envTab.console>pre').height(m.height() - 40);
	}
	$(window).resize(adjust);
	
	function makeItemPl(o, env){
		var pl = itemTpl.clone().addClass('deploy' + o.type).show(),
			hd = pl.children('.head'), bd = pl.children('.form'),
			instGd = bd.seek('instGd');
		
		pl.attr('id', o.id);
		pl.attr('targetId', o.targetId);
		hd.find('.progressBar').data('instSteps',{});
		hd.click(function(){
			bd.toggle();
		});
		hd.find('.progressBar').data('step',3);
		hd.find('.progressBar').attr('name', o.targetId);
		hd.seek('type').html('[' + Cache.deploy.pack[o.type] + ']');
		
		if (o.type != 1 && o.appFrom == 1) {
			pl.addClass('join' + o.appFrom);
			// pl.seek('btn_bottom').html('更新');
			// pl.seek('ok').html('获取更新文件');
		}
// 		if (o.items.length) {
// 			var items='';
// 			for(var i=0;i<o.items.length;i++){
// 				items+='<span>'+o.items[i].itemCode+'</span></br>';
// 			}
// 			pl.seek('itemCode').html(items);
// 		}

		pl.data(o);
		pl.seek('name').html(o.name);
		pl.seek('ver').html(o.version);
		pl.seek('packPath').html(o.packPath);
		pl.seek('path').html(o.deployPath);
		
		var lt = pl.seek('time'), pr = pl.seek('record');
		lt.click(function(){
			alert('TODO 查看最后一次部署的日志');
		}).html(o.lastUpdateTime);
		
		if (o.lastUpdateTime) {
			pr.click(function(){
				App.open({
					ctx: 'deploy',
					title: '单个部署记录',
					action: 'deployRecord',
					model: true,
					params: { planId: pp.id, targetId: o.targetId, env: env }
				});
			}).show();
		}
		
		pl.seek('deployOne').click(function(){
			if (deploying) {
				mac.alert('正在执行{0}，请在此部署结束后再发起。', [deploying]);
				return;
			}
			deploying = 'Msg.deploy.one';
			loading = mac.wait('正在准备部署，请稍候');
			var currentItem = $(this).parent().parent().parent(),
			targetId = currentItem.attr("targetId"),
			cp = currentItem.find('.progressBar[name='+targetId+']'),
			cpi = cp.children('.progress'),
			pa = $('.progressBar[name=progressAll]'),
			pai = pa.children('.progress'),
			os = (pai.data('step') || 0) - (cpi.data('step') || 0);
			// 还原总进度条
			pai.data('step', os);
			pai.width(Math.round(pai.data('step') * 100 / pa.data('step')) + '%');
			// 清空当前打包进度条
			cpi.width(0).data('step', 0);
			// 清空服务器实例进度
			cp.data('instSteps', {});
			tabs.seek(env).find('pre').text('');
// 			pakingNum=1;
			var rd = $(this).parent().parent().seek('deployType').filter(':checked');
			var tdate = new Date();
			var t=tdate.toLocaleString();
			$.post(App.deploy.ctx + '/plan/deploy/one.do' ,{
				planId: pp.id,
				appId: o.targetId,
				env: env,
				sessionId: App.websocket.sessionId,
				deployPolicy: rd.val()
			}, function(rs){
				// pr.show();
				if (loading) {
					loading.close();
					loading = null;
				}
				var ro = mac.eval(rs);
				if (ro.success) {
					lt.html(t);
				} else {
					lt.html('部署失败');
					//mac.alert(ro.data, ro.params);
				}
				deploying = null;
			});
		});
		
		instGd.mac('grid',{
			cols:[{
				field: 'name', title : '节点名', width: 220,
			},{
				field: 'ip', title : 'IP地址', width: 90
			},{
				field: 'targetDeployPort', title : '端口号', width: 60
			},{
				field: 'status', title : '状态', width: 140,
				render:function(r){
					return r.status == 0 ? '未部署':'已部署';
				}
			},{
				field: 'id', title : '操作', width: 110,
				render: function(r){
					return $('<span class="a">部署</span>').click(function(){
						if (deploying) {
							mac.alert('正在执行{0}，请在此部署结束后再发起。', [deploying]);
							return;
						}
						deploying = 'Msg.deploy.inst';
						// 清空日志
						tabs.seek(env).find('pre').text('');
						// 获取部署类型
						var rd = $(this).closest('.itemPl[id='+o.id+']').find('input[name=deployType]').filter(':checked'),
						oldStat = (r.status == 0 ? '未部署':'已部署'),
						// 设置等待进度条
						ss = $(this).parent().parent().seek('status');
						ss.html('<span class="waitImg"><img src = "'+App.deploy.ctx+'/css/img/dpWait.gif"></img></span>');
						// 清空该包当前实例的部署进度和总体部署进度
						var instSteps = hd.find('.progressBar').data('instSteps'),
						cp = pl.find('.progressBar[name='+r.targetId+']'),
						cpi = cp.children('.progress'),
						pa = $('.progressBar[name=progressAll]'),
						pai = pa.children('.progress'),
						aos = (pai.data('step') || 0) - (instSteps[r.serverId] || 0), // 计算总原始进度
						cos = (cpi.data('step') || 0) - (instSteps[r.serverId] || 0); // 计算当前包原始进度
						// 还原总进度条
						pai.data('step', aos);
						pai.width(Math.round(pai.data('step') * 100 / pa.data('step')) + '%');
						// 还原当前包进度条
						cpi.data('step', cos);
						cpi.width(Math.round(cpi.data('step') * 100 / cp.data('step')) + '%')
						// 清空服务器实例的进度
						console.log('original inst ' + r.serverId + ' step: ' + instSteps[r.serverId]);
						instSteps[r.serverId] = 0;
						hd.find('.progressBar').data('instSteps', instSteps);
						
						$.post(App.deploy.ctx + '/plan/deploy/inst.do' ,{
							planId: r.planId,
							appId: r.targetId,
							serverId: r.serverId,
							env: r.env,
							sessionId: App.websocket.sessionId,
							deployPolicy: rd.val()
						},function(rs){
							var ro = mac.eval(rs);
							if (ro.success) {
								// instGd.load();
								ss.html('已部署');
							} else {
								// ss.html(oldStat);
								mac.alert(ro.data, ro.params);
								ss.html('未部署');
							}
							deploying = null;
						})
					});
				}
			},{
				field: 'log', title : '日志', width: 120,
				render: function(r){
					return $('<span class="a">部署日志</a>').click(function(){
						App.open({
							title: '实例部署记录',
							ctx: 'deploy',
							action: 'deployRecord',
							model: true,
							params: { planId: pp.id, env: env, targetId: r.targetId, serverId: r.serverId }
						});
					});
				}
			}] ,
			loader: {
				url: App.deploy.ctx + '/plan/server/list.do',
				params: {
					env:env, targetId: o.targetId,
					planId: o.planId, pageNo: 1, pageSize: 5
				},
				autoLoad: true
			},
			afterLoad: function (dd, po, self) {
				var recTot = po.total;
				if (recTot) {
					hd.find('.progressBar').data('step',3 * recTot);
					var allSteps = tabs.seek(env).seek('progressAll').data('step') || 0;
					allSteps = allSteps + 3 * recTot;
					tabs.seek(env).seek('progressAll').data('step', allSteps)
					console.log('allSteps ' + allSteps);
				}
			},
			pagerLength: 1 
		});
		return pl;
	}
	
	function makeEnvTab(env, items){
		var tab = tabTpl.clone(), hd = tab.children('.head')
			, cs = tab.children('.console');
		
		cs.children('div').click(function(){
			cs.hide().siblings().show();
		});
		hd.seek('records').click(function(){
			App.open({
				title: '全部部署记录',
				ctx: 'deploy',
				action: 'deployRecord',
				model: true,
				params: { planId: pp.id, env: env }
			});
		})
		hd.seek('deployAll').click(function(){
			if (deploying) {
				mac.alert('正在执行{0}，请在此部署结束后再发起。', [deploying]);
				return;
			}
			deploying = 'Msg.deploy.all';
			loading = mac.wait('正在部署，请稍候');
			tab.find('.progress').width(0).data('step', 0);
			// 清空服务器实例进度
			tab.find('.progressBar').data('instSteps',{});
			tab.find('pre').text('');
			var pta = [];
			tab.children('.itemPl').each(function(){
				var pt = $(this).seek('deployType').filter(':checked').attr('value');
				pta.push(pt);
			});
			$.post(App.deploy.ctx + '/plan/deploy/all.do', {
				planId: pp.id,
				env: env,
				targetIds: $.map(items, function(d){
					return d.targetId;
				}).join(','),
				ids: $.map(items, function(d){
					return d.id;
				}).join(','),
				deployPolicies: pta.join(','),
				sessionId: App.websocket.sessionId
			}, function(rs){
				var ro = mac.eval(rs);
				if (loading) {
					loading.close();
					loading = null;
				}
				if (ro.success) {
					//
				} else {
					mac.alert(ro.data, ro.params);
				}
				deploying = null;
			});
		});
		hd.seek('next').click(function(){
			alert('next');
		});
		hd.seek('prev').click(function(){
			alert('prev');
		});
		hd.seek('runLog').click(function(){
			var c = tab.children('.console');
			c.siblings().hide();
			c.show();
		});
		$.each(items, function(i, d){
			tab.append(makeItemPl(d, env));
		});
		hd.children('.progressBar').attr('name', 'progressAll');
		tab.show();
		return { code: env, title: env, el: tab, height: '100%' };
	}
	
	$.post(App.deploy.ctx + '/plan/item/list.do', {
		planId: pp.id,
		type: 0, // 只查询APP
		pageNo: 1,
		pageSize: 999
	}, function(rs){
		var ro = mac.eval(rs), dd = ro.data;
		if (ro.success) {
			tabs.mac('tabs', {
				tabWidth: 80,
				tabHeight: 32,
				items: $.map(dd, function(d, k){
					if (!d.details.length) {
						//TODO 打到日志框
						console.warn('没有针对' + k + '环境配置部署信息');
						return null;
					}
					return makeEnvTab(k, d.details);
				})
			}).selectFirst();
			adjust();
			
		} else {
			mac.alert(dd, ro.params);
		}
	});

	App.websocket.open({
// 		onopen : {
// 			'fn1' : function(e) {
// 			}
// 		},
// 		onclose : {
// 			'fn1' : function(e) {
// 			}
// 		},
// 		onerror : {
// 			'e1' : function(e) {
// 				alert('websocket出现异常');
// 			}
// 		},
		'base': {
			'open': function(o, e, ws){
				// pg.sessionId = o.data;
				App.websocket.sessionId = o.data;
			}
		},
		deploy: {
			'execute': function(o, e, ws) {
				if (loading) {
					loading.close();
					loading = null;
				}
// 				for(var i=0; i<targetArr.length; i++){
// 					if(($(targetArr[i]).attr('targetid')==JSON.parse(event.data).targetId)&&($(targetArr[i]).attr('env')==JSON.parse(event.data).env)){
// 						var steps = ((JSON.parse(event.data).presentCompileStep + 1) / JSON.parse(event.data).totalSteps)*100;
// 						$(targetArr[i]).seek('proBar').attr("style","width:"+steps+"%");
// 						$(targetArr[i]).seek('proBar').attr("percent",steps);
// 						$(targetArr[i]).seek('log').show();
// 						$(targetArr[i]).seek('log').attr("href",App.cache.logUrl.head+JSON.parse(event.data).jobId+App.cache.logUrl.foot);
// 						setPro($(targetArr[i]).parent().parent());
// 					}
// 				}
				var n = '[name=' + o.data.targetId + ']',
					b = pg.find('.progressBar' + n), p = b.children('.progress'),
					pa = pg.seek('progressAll'), pai = pa.children('.progress');
					t = b.data('step'), s = p.data('step') || 0;
					console.log('progressBar: ' + n);
				// 当前包部署进度
				p.data('step', ++s);
				p.width(Math.round(s * 100 / t) + '%');
				// 全部部署进度
				t = pa.data('step');
				s = pai.data('step') || 0;
				pai.data('step', ++s);
				pai.width(Math.round(s * 100 / t) + '%');
				// 如果是单个服务器实例部署，则记录每个实例的推送次数
				var instSteps = b.data('instSteps'),
				runServerId = o.data.serverId;
				console.log('currentServerId : ' + o.data.serverId);
				if (runServerId && instSteps) {
					instSteps[runServerId] = (instSteps[runServerId] || 0) + 1;
					b.data('instSteps', instSteps);
					console.log('instSteps : ' + JSON.stringify(instSteps));
				}
			},
			'export': function(o){
				alert(JSON.stringify(o));
// 				deployingNow++;
// 				deployingNum--;
// 				if(deployingNow==JSON.parse(event.data).jobCount){
// 					deployingNow=0;
// 				}
// 				if(deployingNum==0){
// 				}
			},
			'log': function(o, e, ws) {
				if (loading) {
					loading.close();
					loading = null;
				}
				var d = o.data;
				var content = d.ip + ": " + d.log || '';
				tabs.getTabBody(d.env).find('.envTab>.console>pre').append(content);
				if (d.log && d.log.indexOf(
						'command start_app_one.sh [ebc-dao-service-0.0.1-SNAPSHOT] is success|-\n') > 0) {
					pg.find('.progress').width('100%');
					pg.seek('instGd').find('.td[name=status]').text('已部署');
				}
			}
		}
	});
});
</script>
<div class="tabs"></div>
<div class="envTab hidden">
	<div class="console hidden">
		<div><span class="a">点击返回<span></div>
		<pre></pre>
	</div>
	<div class="head">
		<button name="prev">上一步</button>
		<button name="deployAll">全部部署</button>
		<button name="records">全部部署记录</button>
		<button name="next">下一步</button>
		<div class="progressBar fr">
			<div class="progress"></div>
		</div>
		<span name="runLog" class="a fr">日志跟踪</span>
	</div>
</div>
<div class="itemPl hidden">
	<div class="head">
		<span name="type"></span>
		<span name="name"></span>
		<span name="ver"></span>
		<div class="progressBar fr">
			<div class="progress"></div>
		</div>
	</div>
	<div class="form">
		<div class="item">
			<span class="label">包路径：</span>
			<span class="value" name="packPath"></span>
			<div class="clear"></div>
		</div>
		<div class="item">
			<span class="label">打包时间：</span>
			<span class="a value" name="time"></span>
			<div class="clear"></div>
		</div>
		<div class="item">
			<span class="label">部署路径：</span>
			<span class="value" name="path"></span>
			<div class="clear"></div>
		</div>
		<div class="item">
			<span class="label">部署类型：</span>
			<form class="inline">
				<input type="radio" name="deployType" value="0" checked="checked" />顺序部署
				<input type="radio" name="deployType" value="1" />半数并发
				<input type="radio" name="deployType" value="2" />全量并发
			</form>
			<div class="clear"></div>
		</div>
		<div class="item">
			<span class="label">实例节点：</span>
			<div class="fl" style="height:180px;">
				<div class="grid" name="instGd"></div>
			</div>
			<button name="deployOne" class="fr">部署应用</button>
			<div class="clear"></div>
		</div>
	</div>
	<div class="clear"></div>
</div>